<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" showFooter :title="getTitle" width="600" @ok="handleSubmit" destroyOnClose>
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup name="UserForm">
  import { defineComponent, ref, computed, unref, useAttrs } from "vue"
  import { BasicForm, useForm } from "/@/components/Form/index"
  import { formSchema } from "./user.data"
  import { BasicDrawer, useDrawerInner } from "/@/components/Drawer"
  import { saveOrUpdateUser, getUserDetails } from "./user.api"
  // 声明Emits
  const emit = defineEmits(["success", "register"])
  const attrs = useAttrs()
  const isUpdate = ref(true)
  const rowId = ref("")
  //表单配置
  const [registerForm, { setProps, resetFields, setFieldsValue, validate, updateSchema }] = useForm({
    labelWidth: 80,
    schemas: formSchema,
    showActionButtonGroup: false,
    wrapperCol: { lg: 24, sm: 24 },
  })

  //表单赋值
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    console.timeEnd("user-drawer")

    await resetFields()
    let showFooter = data?.showFooter ?? true
    setDrawerProps({ confirmLoading: false, showFooter })
    isUpdate.value = !!data?.isUpdate
    if (unref(isUpdate)) {
      setDrawerProps({ loading: true })
      try {
        rowId.value = data.record.id
        //查角色/赋值/try catch 处理，不然编辑有问题
        try {
          data.record = await getUserDetails({ userId: data.record.id })
        } catch (error) {}
        if (typeof data.record === "object") {
          setFieldsValue({
            ...data.record,
          })
        }
      } finally {
        setDrawerProps({ loading: false })
      }
    }

    //编辑时隐藏密码/角色列表隐藏角色信息/我的部门时隐藏所属部门
    updateSchema([
      {
        field: "password",
        show: !unref(isUpdate),
      },
      {
        field: "confirmPassword",
        ifShow: !unref(isUpdate),
      },
    ])
    // 隐藏底部时禁用整个表单
    setProps({ disabled: !showFooter })
  })
  //获取标题
  const getTitle = computed(() => (!unref(isUpdate) ? "新增用户" : "编辑用户"))

  //提交事件
  async function handleSubmit() {
    try {
      let values = await validate()
      setDrawerProps({ confirmLoading: true })
      values.userIdentity === 1 && (values.deptIds = "")
      await saveOrUpdateUser(values, unref(isUpdate))
      closeDrawer()
      emit("success", { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } })
    } finally {
      setDrawerProps({ confirmLoading: false })
    }
  }
</script>
